import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Popup {
    id: alarmDialog
    
    x: (parent.width - width) / 2
    y: 100
    width: 450
    height: 280
    modal: false
    focus: true
    closePolicy: Popup.NoAutoClose
    
    property string currentStationId: ""
    property string currentMessage: ""
    property string currentSeverity: "warning"
    property int autoCloseTime: 10 // 秒
    property var currentAlarmInfo: null
    property string reportContent: ""
    
    function showAlarm(stationId, message, severity) {
        currentStationId = stationId
        currentMessage = message
        currentSeverity = severity
        
        // 从 alarmModel 获取最新添加的告警信息（索引0，因为新告警总是添加在最前面）
        if (alarmModel.rowCount() > 0) {
            currentAlarmInfo = alarmModel.getAlarmInfo(0)
        } else {
            currentAlarmInfo = null
        }
        
        open()
        autoCloseTimer.restart()
    }
    
    function generateReport() {
        // 优先使用保存的告警信息，如果没有则从 BaseStationModel 查询
        var stationInfo = null
        
        if (currentAlarmInfo && currentAlarmInfo.stationName) {
            // 使用保存的告警信息（历史快照）
            stationInfo = currentAlarmInfo
        } else {
            // 从 BaseStationModel 查询当前信息
            for (var i = 0; i < baseStationModel.rowCount(); i++) {
                var info = baseStationModel.getStationInfo(i)
                if (info.stationId === currentStationId) {
                    stationInfo = info
                    break
                }
            }
        }
        
        if (!stationInfo) {
            console.log("未找到基站信息:", currentStationId)
            return
        }
        
        // 生成地理位置编号（基于基站ID的数字部分）
        var stationNumber = currentStationId.replace("BS", "").replace(/^0+/, "") // 移除BS前缀和前导零
        var positionNumber = stationNumber + "号位"
        
        // 生成报告内容
        var report = "========== 基站异常处理报告 ==========\n"
        report += "报告生成时间: " + Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss") + "\n"
        report += "处理人员: 系统管理员\n\n"
        
        report += "【基站信息】\n"
        report += "基站ID: " + stationInfo.stationId + "\n"
        report += "基站名称: " + stationInfo.stationName + "\n"
        report += "地理位置: " + positionNumber + "\n\n"
        
        report += "【告警信息】\n"
        report += "告警级别: " + (currentSeverity === "critical" ? "严重" : 
                                currentSeverity === "warning" ? "警告" : "离线") + "\n"
        
        // 获取该基站的告警次数统计
        var stationAlarmCount = 0
        if (typeof alarmModel !== 'undefined') {
            stationAlarmCount = alarmModel.getCountByStation(currentStationId)
        }
        report += "历史告警次数: " + stationAlarmCount + " 次\n"
        
        report += "问题描述: " + currentMessage + "\n\n"
        
        report += "【信号参数】\n"
        report += "信号强度: " + stationInfo.signalStrength.toFixed(1) + "%\n"
        report += "基站状态: " + (stationInfo.status === "normal" ? "正常" :
                                stationInfo.status === "warning" ? "警告" :
                                stationInfo.status === "critical" ? "严重" : "离线") + "\n"
        report += "连接用户数: " + stationInfo.connectedUsers + " 人\n\n"
        
        report += "【地理坐标】\n"
        report += "纬度: " + stationInfo.latitude.toFixed(6) + "°\n"
        report += "经度: " + stationInfo.longitude.toFixed(6) + "°\n\n"
        
        report += "【处理建议】\n"
        if (currentSeverity === "critical") {
            report += "- 立即派遣技术人员到现场检查\n"
            report += "- 检查基站电源和网络连接\n"
            report += "- 必要时启用备用基站\n"
        } else if (currentSeverity === "warning") {
            report += "- 监控信号质量变化趋势\n"
            report += "- 检查周边环境是否有干扰源\n"
            report += "- 安排维护人员例行检查\n"
        } else {
            report += "- 检查基站设备状态\n"
            report += "- 确认网络连接正常\n"
            report += "- 联系设备供应商技术支持\n"
        }
        
        report += "\n========== 报告结束 ==========\n"
        
        // 生成文件名（基于时间戳和基站ID）
        var timestamp = Qt.formatDateTime(new Date(), "yyyyMMdd_HHmmss")
        var fileName = "alarm_report_" + currentStationId + "_" + timestamp + ".txt"
        
        // 保存报告到文件
        saveReportToFile(fileName, report)
        
        // 输出报告到控制台（备份）
        console.log(report)
        
        // 显示报告生成成功的提示
        console.log("✅ 基站", currentStationId, "异常处理报告已生成并保存到:", fileName)
        
        return report
    }
    
    function saveReportToFile(fileName, content) {
        // 通过 NetworkMonitor 的文件写入功能保存报告
        if (typeof networkMonitor !== 'undefined' && networkMonitor.saveReportFile) {
            var success = networkMonitor.saveReportFile(fileName, content)
            if (success) {
                console.log("📄 报告已保存到 reports/" + fileName)
            } else {
                console.log("❌ 文件保存失败")
                console.log("报告内容:")
                console.log(content)
            }
        } else {
            console.log("⚠️ 文件保存功能不可用，输出到控制台:")
            console.log(content)
        }
    }
    
    background: Rectangle {
        color: "white"
        radius: 15
        border.color: currentSeverity === "critical" ? "#e74c3c" : "#f39c12"
        border.width: 3
        
        // 闪烁边框动画
        SequentialAnimation on border.width {
            running: alarmDialog.visible
            loops: Animation.Infinite
            NumberAnimation { to: 5; duration: 500 }
            NumberAnimation { to: 3; duration: 500 }
        }
        
        // 渐变背景
        Rectangle {
            anchors.fill: parent
            radius: parent.radius
            gradient: Gradient {
                GradientStop { 
                    position: 0.0
                    color: currentSeverity === "critical" ? "#fff5f5" : "#fffbf0"
                }
                GradientStop { position: 1.0; color: "white" }
            }
        }
    }
    
    // 自动关闭计时器
    Timer {
        id: autoCloseTimer
        interval: alarmDialog.autoCloseTime * 1000
        onTriggered: alarmDialog.close()
    }
    
    Column {
        anchors.fill: parent
        anchors.margins: 25
        spacing: 20
        
        // 标题栏
        Row {
            width: parent.width
            spacing: 15
            
            Text {
                text: currentSeverity === "critical" ? "🚨" : "⚠️"
                font.pixelSize: 48
                
                // 旋转动画
                RotationAnimator on rotation {
                    running: alarmDialog.visible && currentSeverity === "critical"
                    from: -10
                    to: 10
                    duration: 200
                    loops: Animation.Infinite
                    direction: RotationAnimator.Alternate
                }
            }
            
            Column {
                spacing: 5
                width: parent.width - 63
                
                Text {
                    text: currentSeverity === "critical" ? "严重告警！" : "警告提示"
                    font.pixelSize: 24
                    font.bold: true
                    color: currentSeverity === "critical" ? "#e74c3c" : "#f39c12"
                }
                
                Text {
                    text: Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss")
                    font.pixelSize: 13
                    color: "#7f8c8d"
                }
            }
        }
        
        // 分隔线
        Rectangle {
            width: parent.width
            height: 2
            color: currentSeverity === "critical" ? "#e74c3c" : "#f39c12"
            opacity: 0.3
        }
        
        // 告警信息
        Column {
            width: parent.width
            spacing: 12
            
            Row {
                spacing: 10
                
                Text {
                    text: "基站ID:"
                    font.pixelSize: 14
                    color: "#7f8c8d"
                    font.bold: true
                }
                
                Text {
                    text: currentStationId
                    font.pixelSize: 16
                    color: "#2c3e50"
                    font.bold: true
                }
            }
            
            Column {
                width: parent.width
                spacing: 5
                
                Text {
                    text: "问题描述:"
                    font.pixelSize: 14
                    color: "#7f8c8d"
                    font.bold: true
                }
                
                Rectangle {
                    width: parent.width
                    height: messageText.height + 20
                    color: "#f8f9fa"
                    radius: 8
                    border.color: "#e0e0e0"
                    border.width: 1
                    
                    Text {
                        id: messageText
                        anchors.centerIn: parent
                        width: parent.width - 20
                        text: currentMessage
                        font.pixelSize: 15
                        color: "#2c3e50"
                        wrapMode: Text.WordWrap
                    }
                }
            }
        }
        
        Item { height: 5 }
        
        // 按钮栏
        Row {
            anchors.horizontalCenter: parent.horizontalCenter
            spacing: 15
            
            Button {
                text: "立即处理"
                width: 120
                height: 40
                
                background: Rectangle {
                    color: parent.pressed ? "#c0392b" : parent.hovered ? "#e74c3c" : "#e74c3c"
                    radius: 8
                }
                
                contentItem: Text {
                    text: parent.text
                    color: "white"
                    font.pixelSize: 14
                    font.bold: true
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
                
                onClicked: {
                    // 生成详细报告并显示
                    var report = generateReport()
                    reportContent = report
                    alarmDialog.close()
                    reportPopup.open()
                }
            }
            
            Button {
                text: "稍后处理"
                width: 120
                height: 40
                
                background: Rectangle {
                    color: parent.pressed ? "#7f8c8d" : parent.hovered ? "#95a5a6" : "#bdc3c7"
                    radius: 8
                }
                
                contentItem: Text {
                    text: parent.text
                    color: "white"
                    font.pixelSize: 14
                    font.bold: true
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
                
                onClicked: {
                    alarmDialog.close()
                }
            }
        }
    }
    
    // 进入动画
    enter: Transition {
        NumberAnimation {
            property: "opacity"
            from: 0
            to: 1
            duration: 300
        }
        NumberAnimation {
            property: "scale"
            from: 0.5
            to: 1
            duration: 300
            easing.type: Easing.OutBack
        }
    }
    
    // 退出动画
    exit: Transition {
        NumberAnimation {
            property: "opacity"
            from: 1
            to: 0
            duration: 200
        }
        NumberAnimation {
            property: "scale"
            from: 1
            to: 0.8
            duration: 200
        }
    }
    
    // 报告显示弹窗
    Popup {
        id: reportPopup
        x: (parent.width - width) / 2
        y: 50
        width: 600
        height: 500
        modal: true
        focus: true
        closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
            
        background: Rectangle {
            color: "white"
            radius: 15
            border.color: "#3498db"
            border.width: 2
            
            // 渐变背景
            Rectangle {
                anchors.fill: parent
                radius: parent.radius
                gradient: Gradient {
                    GradientStop { position: 0.0; color: "#f0f8ff" }
                    GradientStop { position: 1.0; color: "white" }
                }
            }
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 15
            
            // 标题栏
            RowLayout {
                width: parent.width
                
                Text {
                    text: "📋 基站异常处理报告"
                    font.pixelSize: 22
                    font.bold: true
                    color: "#2c3e50"
                }
                
                Item {
                    Layout.fillWidth: true
                }
                
                Button {
                    width: 100
                    height: 35
                    text: "关闭"
                    
                    background: Rectangle {
                        color: parent.pressed ? "#7f8c8d" : parent.hovered ? "#95a5a6" : "#bdc3c7"
                        radius: 8
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font.pixelSize: 14
                        font.bold: true
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: reportPopup.close()
                }
            }
            
            // 分隔线
            Rectangle {
                width: parent.width
                height: 2
                color: "#3498db"
                opacity: 0.3
            }
            
            // 报告内容
            ScrollView {
                width: parent.width
                height: parent.height - 100
                
                ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
                
                Text {
                    width: reportPopup.width - 60
                    text: reportContent || "未生成报告内容"
                    font.pixelSize: 13
                    font.family: "Consolas, 'Courier New', monospace"
                    color: "#2c3e50"
                    wrapMode: Text.WordWrap
                    lineHeight: 1.5
                }
            }
        }
        
        // 进入动画
        enter: Transition {
            NumberAnimation {
                property: "opacity"
                from: 0
                to: 1
                duration: 200
            }
            NumberAnimation {
                property: "scale"
                from: 0.9
                to: 1
                duration: 200
            }
        }
        
        // 退出动画
        exit: Transition {
            NumberAnimation {
                property: "opacity"
                from: 1
                to: 0
                duration: 150
            }
            NumberAnimation {
                property: "scale"
                from: 1
                to: 0.9
                duration: 150
            }
        }
    }
}

